package com.project.restaurant.order.dto;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.project.restaurant.common.key.SessionAttribute;
import com.project.restaurant.common.util.SpringUtil;
import com.project.restaurant.order.enums.OrderState;
import com.project.restaurant.pojo.Meal;
import com.project.restaurant.pojo.Order;
import com.project.restaurant.pojo.OrderDetailItem;
import com.project.restaurant.pojo.User;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class PlaceOrderInfo {

    @ApiModelProperty(value = "座位id;后台功能没有添加，暂时不传")
    @NotNull
    private Integer seatId = 1;
    @ApiModelProperty(value = "订单描述")
    private String orderDemand;
    @ApiModelProperty(value = "下单购买的餐点列表",required = true)
    @Valid
    @NotEmpty
    private List<PlaceMealItem> mealItems;

    public Order getOrder() {
        User user = (User) SpringUtil.getHttpSession().getAttribute(SessionAttribute.NOW_LOGIN_USER);
        Order order = new Order()
                .setUserId(user.getUserId())
                .setSeatId(this.getSeatId())
                .setOrderDemand(this.getOrderDemand())
                .setOrderState(OrderState.WAITING_PAY.getOrderState())
                .setOrderPurchaseTime(LocalDateTime.now());
        return order;
    }

    public List<OrderDetailItem> getOrderItems(String orderId, List<Meal> meals) {
        List<OrderDetailItem> orderItems = new ArrayList<>();
        for (PlaceMealItem item : mealItems) {
            for (Meal meal : meals) {
                if (item.getMealId() == meal.getMealId()) {
                    OrderDetailItem orderDetailItem = new OrderDetailItem();
                    orderDetailItem
                            .setOrderId(orderId)
                            .setMealId(meal.getMealId())
                            .setPurchasingMealPrice(meal.getMealPrice())
                            .setPurchaseNum(item.getPurchaseNum());
                    orderItems.add(orderDetailItem);
                }
            }
        }
        return orderItems;
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Accessors(chain = true)
    public static class PlaceMealItem {
        @ApiModelProperty(value = "餐点id",required = true)
        @NotNull
        private Integer mealId;

        /**
         * 购买的数量
         */
        @ApiModelProperty(value = "购买数量",required = true)
        @NotNull
        private Integer purchaseNum;

    }

}

